package com.yoomiito.app.ui.college.detail

import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.text.TextUtils
import android.view.View
import cn.droidlover.xdroidmvp.net.XApi
import cn.jzvd.Jzvd
import cn.jzvd.JzvdStd
import com.yoomiito.app.Constant
import com.yoomiito.app.pay.NewPayUtils
import com.yoomiito.app.pay.PayInfo
import com.yoomiito.app.pay.PayResult
import com.yoomiito.app.R
import com.yoomiito.app.adapter.ViewPagerFragmentAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.colleage.SubjectDetailInfo
import com.yoomiito.app.model.my.MyRemainMoneyInfo
import com.yoomiito.app.ui.order.sureorder.BuyResultActivity
import com.yoomiito.app.share.ui.NewInviteShareActivity
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.college.VideoLayout
import com.yoomiito.app.utils.*
import com.yoomiito.app.utils.video.VideoUtils
import com.yoomiito.app.widget.dialog.TipDialog
import com.yoomiito.app.widget.videoplayer.VideoPlayer
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.act_subject_detail.*
import kotlinx.android.synthetic.main.title_bar.*
import org.greenrobot.eventbus.EventBus
import java.util.*
import java.util.concurrent.TimeUnit


class SubjectDetailActivity : BaseActivity<SubjectDetailPresenter>() {

    companion object {
        fun start(context: Context, id: Long, buy: Boolean, productId: Long) {
            val intent = Intent(context, SubjectDetailActivity::class.java)
            intent.putExtra(Constant.ID, id)
            intent.putExtra(Constant.KEY, buy)
            intent.putExtra(Constant.ProductId, productId)
            context.startActivity(intent)

        }
    }

    private val mSubjectIntroductionFragment = SubjectIntroductionFragment()
    private val mSubjectTableFragment2 = SubjectTableFragment2()
    private var mId: Long = 0
    private var mBuy = false
    private var mProductId: Long = 0
    private lateinit var mMoneyInfo: MyRemainMoneyInfo
    private lateinit var videoLayout: VideoLayout
    private lateinit var mTipDialog: TipDialog
    private lateinit var mSubjectInfo: SubjectDetailInfo
    private val tabs = arrayOf("介绍", "目录")
    private val mFragments = ArrayList<androidx.fragment.app.Fragment>()
    private var payUtils: NewPayUtils? = null
    private var yoMoneyPay = 0//1优币抵扣，0不抵扣
    var mPayOrderId: String? = null
    var mPayMoney: String? = null//应付金额  来自于服务器
    var mOrderType: Int = 4
    private lateinit var mQueryId: String
    private lateinit var mPayType: String
    private var mCurrentPlayPosition = 0
    private var mVideoStatus = VideoPlayer.UnPlay
    private lateinit var disposable:Disposable
    override fun getLayoutId(): Int = R.layout.act_subject_detail

    override fun newP(): SubjectDetailPresenter = SubjectDetailPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        mId = intent.getLongExtra(Constant.ID, 0)
        mBuy = intent.getBooleanExtra(Constant.KEY, false)
        mProductId = intent.getLongExtra(Constant.ProductId, 0)
        share_tv.background = ColorUtils.background(R.color.color_FF035B,DensityUtil.dp2px(4f).toFloat())
        tv_center.text = "课程详情"
        iv_back_left.setOnClickListener { finish() }
        right_iv.setImageResource(R.drawable.icon_share)
        right_iv.setOnClickListener { NewInviteShareActivity.start(this, AllCode.College, mId) }

        videoLayout = VideoLayout(this, frameLayout)
        videoLayout.videoState = {
            if (it!=VideoPlayer.PLAY_PROGRESS){
                mVideoStatus = it
            }
            L.i("原始状态：$mVideoStatus")
            when (it) {
                VideoPlayer.START_PLAY -> {
                    share_view.visibility = View.GONE
                    viewPager.currentItem = 2
                    VideoUtils.savePlayRecord(mProductId, mCurrentPlayPosition)//记录播放位置
                }
                VideoPlayer.PLAYING -> if (share_view?.visibility != View.GONE) share_view?.visibility = View.GONE
                VideoPlayer.PLAY_COMPLETE -> {
                    mSubjectTableFragment2.updateData(if (mCurrentPlayPosition + 1 == mSubjectInfo.tableInfo.size) 0 else mCurrentPlayPosition + 1)
                }
            }
        }

        initViewPager()
        initTabLayout()
        initVideoStatusBtn()
        showLoading()
        disposable = Observable.timer(500, TimeUnit.MILLISECONDS)
                //                .compose(bindToLifecycle())
                .compose(XApi.changeScheduler())
                .subscribe {
                    p.getSubjectInfo(mId)
                }
    }

    private fun initViewPager() {
        mSubjectTableFragment2.onItemSelectListener = { position, tableInfo ->
            mCurrentPlayPosition = position
            videoLayout.setVideoSource(tableInfo.course_url, tableInfo.course_url_img, true)
        }
        mFragments.add(mSubjectIntroductionFragment)
        mFragments.add(mSubjectTableFragment2)
        viewPager.currentItem = 1
        viewPager.adapter = ViewPagerFragmentAdapter(supportFragmentManager, mFragments)
    }

    private fun initTabLayout() {
        for (i in tabs.indices) {
            tabLayout.addTab(tabLayout.newTab().setText(tabs[i]))
        }
        tabLayout.setupWithViewPager(viewPager)
        for (i in tabs.indices) {
            tabLayout.getTabAt(i)!!.text = tabs[i]
        }
//        tabLayout.getTabAt(0)!!.select()
//        tabLayout.post { TabLayoutUtils.setIndicator(tabLayout, 24, 24) }
    }

    private fun initVideoStatusBtn() {
//        videoStatusBtn.text = "立即购买"
        videoStatusBtn.tag = 1
        videoStatusBtn.setOnClickListener {
            when (it.tag) {
                1 -> p.createOrder(mId)//立即购买
                3 -> applyVIP()//领取课程福利
                4 -> NewInviteShareActivity.start(this, AllCode.College, mId)//分享赚
            }
        }
    }

    /**
     * 购买成功 显示课程
     */
    private fun switchVideo() {
        videoLayout.showVideo()
        if (UserInfoConfig.getUser().course_status == 0 && !mSubjectInfo.goodsDetail.isTwenty_seconds) {
            videoLayout.progress = {
                if (it <= 0) {
                    if ((videoStatusBtn.tag as Int) < 3) {
                        videoStatusBtn.text = "点击领取课程福利"
                        videoStatusBtn.isEnabled = true
                        setVideoStatusBtnBackgroundColor(R.color.color_vip_bg)
                        videoStatusBtn.tag = 3
                        p.postTwentySeconds(mId)//看够20s 上传课程记录
                    }
                } else {
                    videoStatusBtn.text = "点击领取课程福利($it)"
                }
            }
        }
        val tableInfo = mSubjectInfo.tableInfo[mCurrentPlayPosition]
        videoLayout.setVideoSource(tableInfo.course_url, tableInfo.course_url_img, false)
        if (UserInfoConfig.getUser().course_status == 0) {//0 还没有点击成为VIP  1 已经成为VIP
            if (mSubjectInfo.goodsDetail.isTwenty_seconds) {
                videoLayout.showTip(false)
                videoStatusBtn.text = "点击领取课程福利"
                videoStatusBtn.isEnabled = true
                setVideoStatusBtnBackgroundColor(R.color.color_vip_bg)
                videoStatusBtn.tag = 3
            } else {
                videoLayout.showTip(true)
                videoStatusBtn.text = "点击领取课程福利"
                videoStatusBtn.isEnabled = false
                videoStatusBtn.tag = 2
                setVideoStatusBtnBackgroundColor(R.color.color_gray_CCCCCC)
            }
        } else {
            share_view.visibility = View.VISIBLE
            right_iv.visibility = View.VISIBLE
            share_tv.text = "分享赚${SpannableUtils.handlePrice(mSubjectInfo.goodsDetail.get_money)}"
            videoStatusBtn.text = "分享赚¥${SpannableUtils.handlePrice(mSubjectInfo.goodsDetail.get_money)}"
            videoStatusBtn.tag = 4
            setVideoStatusBtnBackgroundColor(R.color.color_FF035B)
        }
    }

    /**
     * 设置底部按钮背景颜色
     */
    private fun setVideoStatusBtnBackgroundColor(color: Int) {
        val dg = videoStatusBtn.background as GradientDrawable
        dg.setColor(ResUtil.getColor(color))
    }

    /**
     * 购买成功 需要刷新视频 刷新目录 刷新商学院列表
     */
    private fun paySuccessUpdateData() {
        switchVideo()
        mSubjectTableFragment2.buySuccessUpdateData(true)

        //购买成功 通知列表刷新数据
        val eventMessage = EventMessage()
        eventMessage.eventType = AllCode.UPDATE_DATA
        EventBus.getDefault().post(eventMessage)
    }

    /**
     * 支付弹窗
     */
    private fun showPayDialog() {
        if (payUtils == null) {
            payUtils = NewPayUtils(this)
            payUtils?.payResultListener = { payResult ->
                when (payResult.payState) {
                    PayResult.PaySuccess -> {
                        //刷新数据 密码支付成功
                        paySuccessUpdateData()
                    }
                    PayResult.PayFail -> {
                        val eventMessage = EventMessage()
                        eventMessage.code = AllCode.Fail
                        payResult(eventMessage)
                    }
                    PayResult.CallOtherPayUtils -> {
                        mQueryId = payResult.queryOrderId
                        mPayType = payResult.payType
                    }
                }
            }
        }
        payUtils?.payInfo = PayInfo(mPayOrderId!!,
                mMoneyInfo.money,//待支付金额
                mOrderType,
                0,
                mMoneyInfo.money,
                "¥$mPayMoney",//待支付金额
                AllUtils.moneyCompare(mMoneyInfo.money, mPayMoney)//待支付金额
        )
        payUtils?.showDialog()
    }

    /**
     * 申请成为VIP弹窗
     */
    private fun applyVIP() {
        mTipDialog = TipDialog(this)
        mTipDialog.setTitle("确认领取课程福利吗？")
                .setContent("领取成功后即可享受分享赚佣金")
                .setCancelText("取消")
                .setSureText("确认")
                .setClickListener {
                    mTipDialog.dismiss()
                    p.requestVIP(mId)
                }
                .show()

    }

    //设置余额
    fun setYouMi(moneyInfo: MyRemainMoneyInfo) {
        this.mMoneyInfo = moneyInfo
        showPayDialog()
    }

    //微信 支付宝 支付结果  根据查询订单状态 跳到支付结果
    fun payResult(eventMessage: EventMessage) {
        dismissLoading()
        when (eventMessage.code) {
            AllCode.Success -> {
                paySuccessUpdateData()
            }
            AllCode.Fail -> {
                eventMessage.goodsType = AllCode.College
                BuyResultActivity.start(this, eventMessage)
            }
        }
    }

    /**
     * 设置数据
     * 如果已购买 显示视频
     */
    fun setData(info: SubjectDetailInfo) {
        mSubjectInfo = info
        if (mBuy) {
            switchVideo()
        } else {
            videoLayout.showPic()
            videoLayout.setPicUrl(info.goodsDetail.pict_url)
            videoStatusBtn.text = "立即购买"
            setVideoStatusBtnBackgroundColor(R.color.color_FF035B)
        }
        info.goodsDetail.desc.add(0, if (UserInfoConfig.getUser().course_status == 0) info.goodsDetail.course_welfare_befor else info.goodsDetail.course_welfare_after)
        mSubjectIntroductionFragment.setData(info.goodsDetail)

        setTableData(mBuy)
        dismissLoading()
    }

    /**
     * 设置目录数据
     */
    private fun setTableData(buy: Boolean) {
        for (it in VideoUtils.getPlayRecord()) {//根据缓存记录 获取当前课程的播放位置
            if (it.productId == mProductId) {
                mCurrentPlayPosition = it.playPosition
            }
        }
        mSubjectInfo.tableInfo[if (mCurrentPlayPosition + 1 > mSubjectInfo.tableInfo.size) 1 else mCurrentPlayPosition].isSelected = true
        for (it in mSubjectInfo.tableInfo) {
            it.isClick = buy
        }
        mSubjectTableFragment2.setData(mSubjectInfo.tableInfo)
    }

    /**
     * 申请VIP成功
     *  1.刷新用户信息
     *  2.更换课程介绍福利图
     *  3.底部按钮可点击
     */
    fun requestVIPResult(result: Boolean) {
        updateUserInfo()
        if (result) {
            updateUserInfo()
            mSubjectIntroductionFragment.updateInfo(mSubjectInfo.goodsDetail.course_welfare_after)
            L.i("现在状态：$mVideoStatus")
            L.i("判断：${(mVideoStatus==VideoPlayer.PLAYING) or (mVideoStatus==VideoPlayer.START_PLAY)}")
            share_view.visibility = if ((mVideoStatus==VideoPlayer.PLAYING) || (mVideoStatus==VideoPlayer.START_PLAY)) View.GONE else View.VISIBLE
            right_iv.visibility = View.VISIBLE
            share_tv.text = "分享赚${SpannableUtils.handlePrice(mSubjectInfo.goodsDetail.get_money)}"

            videoStatusBtn.text = "分享赚¥${SpannableUtils.handlePrice(mSubjectInfo.goodsDetail.get_money)}"
            videoStatusBtn.tag = 4
            setVideoStatusBtnBackgroundColor(R.color.color_FF035B)
        }
    }

    override fun eventMessage(eventMessage: EventMessage) {
        super.eventMessage(eventMessage)
        if (Constant.PAY_RESULT == eventMessage.eventType) {
            if (TextUtils.isEmpty(mQueryId)) {
                showToast("订单状态异常")
                return
            }
            showLoading()
            p!!.queryOrder(mQueryId, mPayType)
        }
    }

    fun error() {
        dismissLoading()
        YMToast.showText("数据获取失败，请稍后再试")
        finish()
    }

    fun error(msg:String) {
        if (!msg.isNullOrEmpty())msg.showToast()
        finish()
    }

    override fun onResume() {
        super.onResume()
        JzvdStd.goOnPlayOnResume()
    }

    override fun onBackPressed() {
        if (Jzvd.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        JzvdStd.goOnPlayOnPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        payUtils?.release()
        JzvdStd.releaseAllVideos()
    }

}
